package com.qf.pickname.service.impl;

import com.qf.pickname.dao.StudentDao;
import com.qf.pickname.entity.Student;
import com.qf.pickname.service.StudentService;
import com.qf.pickname.utils.StudentDataStore;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

// 添加该注解，会让springboot启动时扫描到当前类，并且帮我们创建这个类的对象
@Service
public class StudentServiceImpl implements StudentService {

    public static final String[] DEFAULT_AVATAR = {"1.webp","2.webp","3.webp","4.webp","5.webp"};


    @Autowired
    private StudentDao studentDao;

    @Override
    public Student randomStudent() {
        Random random = new Random();
        Integer count = studentDao.getStudentCount();
        int index = random.nextInt(count);
        Student student = studentDao.getStudentByIndex(index);

        // 给学生添加默认的头像
        if (student.getAvatar()==null){
            int i = random.nextInt(5);
            String avatar = DEFAULT_AVATAR[i];
            student.setAvatar(avatar);
        }

        return student;
    }

    @Override
    public Boolean addStudent(String name, String sex) {

        //1. 判断name是否有重名的
        // 查询name对应的学生是否存在
        Student student = studentDao.getStudentByName(name);
        if (student!=null){
            System.out.println("学生的名字重复了");
            return false;
        }

        //2. 添加学生
        studentDao.addStudent(name,sex);

        return true;
    }

    @Override
    public Student randomStudentPro() {

        //1. 判断 学生的状态是否为0，如果为0，就把状态改为1；如果不是0，再随机选取一个
        while (studentDao.hasNextStudent()){ // 如果还有没点到的学生
            Student student = randomStudent();
            if (student.getChecked()==0){
                student.setChecked(1); // 设置该学生已经被点过名了
                return student;
            }
        }
        return null;
    }

    @Override
    public Student randomStudentPlus() {

        //1. 查找没有被点中的学生，获取一个List
        List<Student> studentList = studentDao.getUncheckedStudentList();
        if (studentList.size()==0){
            return null;
        }
        //2. 在上面的list中进行随机点名，并设置被点中的学生
        int i = new Random().nextInt(studentList.size());
        Student student = studentList.get(i);
        student.setChecked(1);

        return student;
    }

    @Override
    public Student randomStudentProMax() {


        return null;
    }

    @Override
    public Student getStudentByname(String name) {
        Student studentByName = studentDao.getStudentByName(name);

        return studentByName;

    }
}
